const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();

// JWT密钥
const JWT_SECRET = process.env.JWT_SECRET;
// JWT过期时间
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

// 生成JWT令牌
const generateToken = (userId) => {
  return jwt.sign({ id: userId }, JWT_SECRET, {
    expiresIn: JWT_EXPIRES_IN,
  });
};

// 验证JWT令牌
const verifyToken = (token) => {
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    return { valid: true, expired: false, decoded };
  } catch (error) {
    return {
      valid: false,
      expired: error.name === 'TokenExpiredError',
      decoded: null,
    };
  }
};

module.exports = {
  generateToken,
  verifyToken,
};